﻿<%@ WebHandler Language="C#" Class="MyAjaxHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Reflection;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Newtonsoft.Json;
using Hangjing.WebCommon;

/// <summary>
/// 处理一般ajax请求:注意，所有方法是不能有参数的
/// </summary>
public class MyAjaxHandler : HandlerBase, System.Web.SessionState.IRequiresSessionState
{
    /// <summary>
    /// 发送饿了么订单到系统
    /// </summary>
    /// <returns></returns>
    public string sendEleOrder2system()
    {

        string orderid = WebUtility.InputText(base._httpReuqest["orderid"]).Trim();

        CustorderInfo infoaddress = new shopeleCustorder().GetModel(orderid);

        PointsInfo shop = new Points().GetModel(infoaddress.TogoId);


        ETogoLocalInfo info = new ETogoLocalInfo();
        ETogoLocal bll = new ETogoLocal();

        info = bll.GetInfoById(shop.Unid.ToString());

        infoaddress.tempcode = "";
        infoaddress.ReveVar1 = shop.sentorg;
        infoaddress.OldPrice = infoaddress.OrderSums;
        infoaddress.cityid = shop.cityid;
        infoaddress.TogoId = shop.Unid;
        infoaddress.paytime = Convert.ToDateTime("1970-1-1");
        infoaddress.IsShopSet = 1;
        infoaddress.ReveDate1 = DateTime.Now;
        infoaddress.Commission = WebHelper.getShopCommission(infoaddress.OrderSums, shop);
        infoaddress.settlecycle = shop.PType;
        infoaddress.OrderAddress = shop.Name;
        infoaddress.InUse = shop.PHead;
        infoaddress.deliverheaderid = shop.IsCallCenter;
        infoaddress.OldStatus = Convert.ToInt32(shop.PEnd);
        Custorder orderdal = new Custorder();

        apiResultInfo rs = new apiResultInfo();
        rs.state = 0;


        IList<Hangjing.Model.ETogoShoppingCart> Foods = new List<Hangjing.Model.ETogoShoppingCart>();

        Hangjing.Model.ETogoShoppingCart myshopcart = new Hangjing.Model.ETogoShoppingCart();
        myshopcart.TogoId = infoaddress.TogoId;
        myshopcart.sendfree = 0;
        //满多少元免配送费未处理
        myshopcart.ItemList = null;
        myshopcart.latlng = infoaddress.ReveVar2;

        IList<ETogoShoppingCartInfo> foodlist = new List<ETogoShoppingCartInfo>();

        IList<FoodlistInfo> orderfoods = new shopeleFoodlist().GetAllByOrderID(orderid);

        foreach (var item in orderfoods)
        {

            ETogoShoppingCartInfo cartfood = new ETogoShoppingCartInfo();
            cartfood.PId = item.FoodUnid;
            cartfood.PName = item.FoodName;
            cartfood.PNum = item.FCounts;
            cartfood.PPrice = item.FoodPrice;
            cartfood.Currentprice = cartfood.PPrice;
            cartfood.Foodcurrentprice = cartfood.PPrice;
            cartfood.Remark = "";

            foodlist.Add(cartfood);


        }
        myshopcart.ItemList = foodlist;
        Foods.Add(myshopcart);


        ////这里进行所有的判断
        IList<ROrderinfo> mylist = orderdal.SubmitOrder(Foods, infoaddress);

        if (mylist != null)
        {
            if (infoaddress.paystate == 1)
            {
                orderdal.UpdatePayState(infoaddress);
            }

            rs.state = 1;
            rs.data = JsonConvert.DeserializeObject("{\"id\":\"" + infoaddress.orderid + "\",\"lat\":\"" + info.Lat + "\",\"lng\":\"" + info.Lng + "\"}");

            WebUtility.excutesql("UPDATE dbo.shopeleCustorder SET IsShopSet = 1,ReveDate1 = GETDATE() WHERE orderid = '" + orderid + "'");


        }
        else
        {
            rs.msg = "系统错误，请稍后";
        }



        return JsonConvert.SerializeObject(rs);
    }




    /// <summary>
    ///  自动调度 自动派给1公里内距离最近、没单待岗的骑士
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public string shopautodispatch()
    {
        string lat = WebUtility.InputText(base._httpReuqest["lat"]);
        string lng = WebUtility.InputText(base._httpReuqest["lng"]);
        string orderid = WebUtility.InputText(base._httpReuqest["id"]);
        int cityid = Convert.ToInt32(WebUtility.InputText(base._httpReuqest["cityid"]));
        int gid = Convert.ToInt32(WebUtility.InputText(base._httpReuqest["gid"]));

        apiResultInfo rs = new apiResultInfo();
        rs.state = 1;

        int did = new Custorder().ShopAutoDispatch(lat, lng, orderid, cityid, gid);
        if (did == 0)
        {
            rs.msg = "附近没有待岗骑士，订单直接转由客服调度";
            rs.state = 0;
            WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar1 = '0' WHERE orderid = '" + orderid + "'");
        }
        else
        {
            DeliverInfo deliver = new Deliver().GetModel(did);
            rs.msg = "已经调度给配送员：" + deliver.Name + "(" + deliver.Phone + ")" + "!";

        }
        return JsonConvert.SerializeObject(rs);

    }



    /// <summary>
    /// 订单发给客服调度
    /// </summary>
    public string dispatch2Service()
    {
        string orderid = WebUtility.InputText(base._httpReuqest["id"]);
        WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar1 = '0' WHERE orderid = '" + orderid + "'");
        return "1";

    }


    /// <summary>
    /// 商家发人
    /// </summary>
    /// <returns></returns>
    public string shopSpreadOne2deliver()
    {
        int did = Convert.ToInt32(WebUtility.InputText(base._httpReuqest["did"]));
        string delivername = Context.Server.UrlDecode(WebUtility.InputText(base._httpReuqest["name"]));
        string IdList = WebUtility.InputText(base._httpReuqest["oids"]);

        OrderDeliver dalod = new OrderDeliver();
        OrderDeliverInfo odmodel = odmodel = new OrderDeliverInfo();
        odmodel.Orderid = IdList;
        odmodel.DeliverId = did;
        odmodel.DeliverName = delivername;
        odmodel.Dispatcher = "商家微信";
        odmodel.DispatchTime = DateTime.Now;
        odmodel.DeliveryTime = DateTime.Now;
        odmodel.Inve1 = 0;
        odmodel.Inve2 = "";
        odmodel.Section = "3";

        dalod.Save(odmodel);

        new Custorder().AddOrderRecord(odmodel.Orderid, 7, odmodel.Dispatcher, "商家微信调度给配送员");
        WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar1 = '0' WHERE orderid = '" + odmodel.Orderid + "'");

        NoticeHelper notice = new NoticeHelper(Context, did.ToString(), IdList);
        notice.sendOrderToDeliver();

        return "1";

    }



    /// <summary>
    /// 计算跑腿距离，配送费
    /// </summary>
    /// <returns></returns>
    public string expressDistanceAndFee()
    {

        string flat = WebUtility.InputText(base._httpReuqest["flat"]);
        string flng = WebUtility.InputText(base._httpReuqest["flng"]);
        string tlat = WebUtility.InputText(base._httpReuqest["tlat"]);
        string tlng = WebUtility.InputText(base._httpReuqest["tlng"]);
        string orderType = WebUtility.InputText(base._httpReuqest["orderType"]);//  0:"送"; 1: "买



        SendfeeInfo info = new SendfeeInfo();
        info.ShopID = Convert.ToInt32(WebUtility.InputText(base._httpReuqest["cityid"]));
        info.cityname = WebUtility.InputText(Context.Server.UrlDecode(base._httpReuqest["cityname"]));
        info.sendtime = Convert.ToDateTime((Context.Server.UrlDecode(base._httpReuqest["sendtime"])));

        info.latlng = new latlnginfo();
        info.latlng.ulat = flat;
        info.latlng.ulng = flng;
        info.latlng.slat = tlat;
        info.latlng.slng = tlng;

        SendFee fee = new SendFee(info);
        SendInfo model = fee.getExpressSendFee();


        return JsonConvert.SerializeObject(model);
    }


    /// <summary>
    /// 发布订单
    /// </summary>
    /// <returns></returns>
    public string publishorder()
    {
        int shopid = Convert.ToInt32(base._httpReuqest["hftid"]);
        PointsInfo shop = new Points().GetModel(shopid);
        ETogoLocalInfo info = new ETogoLocalInfo();
        ETogoLocal bll = new ETogoLocal();

        info = bll.GetInfoById(shop.Unid.ToString());

        CustorderInfo infoaddress = new CustorderInfo();
        infoaddress.OrderRcver = "";
        infoaddress.AddressText = WebUtility.InputText(base._httpReuqest["tbaddress"]) + WebUtility.InputText(base._httpReuqest["tbaddressdetail"]);
        infoaddress.OrderComm = WebUtility.InputText(base._httpReuqest["OrderComm"]);
        infoaddress.OrderAttach = WebUtility.InputText(base._httpReuqest["OrderAttach"]);
        infoaddress.paymode = 4;
        infoaddress.SendTime = Convert.ToDateTime(WebUtility.InputText(base._httpReuqest["tbSentTime"]));
        infoaddress.tempcode = "";
        infoaddress.CustomerName = "";
        infoaddress.UserId = 0;
        infoaddress.fromweb = ((int)OrderSource.ShopCenter).ToString();
        infoaddress.ReveVar1 = shop.sentorg;

        string ulat = WebUtility.InputText(base._httpReuqest["hidlat"]);
        string ulng = WebUtility.InputText(base._httpReuqest["hidlng"]);

        if (ulat == SectionProxyData.GetSetValue(4))
        {
            ulat = "0";
            ulng = "0";
        }

        infoaddress.ReveVar2 = "{'ulat':'" + ulat + "','ulng':'" + ulng + "','slat':'" + info.Lat + "','slng':'" + info.Lng + "'}";
        infoaddress.OrderSums = Convert.ToDecimal(base._httpReuqest["tbPrice"]);
        infoaddress.shopdiscountmoney = Convert.ToDecimal(base._httpReuqest["tbshopdiscountmoney"]);
        infoaddress.shoptip = Convert.ToDecimal(base._httpReuqest["hftip"]);

        infoaddress.shopdiscountmoney += infoaddress.shoptip;


        infoaddress.OldPrice = infoaddress.OrderSums;
        infoaddress.cityid = shop.cityid;
        infoaddress.TogoId = shop.Unid;
        infoaddress.P2Sign = "";
        infoaddress.paytime = Convert.ToDateTime("1970-1-1");
        infoaddress.IsShopSet = 1;
        infoaddress.ReveDate1 = DateTime.Now;
        infoaddress.cardpay = Convert.ToDecimal(base._httpReuqest["tbcardpay"]);
        infoaddress.cardids = "";
        infoaddress.Commission = WebHelper.getShopCommission(infoaddress.OrderSums, shop);
        infoaddress.settlecycle = shop.PType;
        infoaddress.Advance = Convert.ToDecimal(base._httpReuqest["tbAdvance"]);
        infoaddress.Mergeorderremark = "";
        infoaddress.OrderAddress = shop.Name;
        infoaddress.SystemUserId = Convert.ToInt32(base._httpReuqest["ddlSystemUserId"]);
        infoaddress.InUse = shop.PHead;
        infoaddress.deliverheaderid = shop.IsCallCenter;
        infoaddress.OldStatus = Convert.ToInt32(shop.PEnd);

        Custorder orderdal = new Custorder();



        apiResultInfo rs = new apiResultInfo();
        rs.state = 0;

        if (orderdal.AddTBOrder(infoaddress) > 0)
        {
            rs.state = 1;
            rs.data = JsonConvert.DeserializeObject("{\"id\":\"" + infoaddress.orderid + "\",\"lat\":\"" + info.Lat + "\",\"lng\":\"" + info.Lng + "\"}");

            if (Convert.ToInt32(base._httpReuqest["hfisselfdispatch"]) == 1)
            {
                WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar1 = '10' WHERE orderid = '" + infoaddress.orderid + "'");
            }

            if (base._httpReuqest["hidhasaddr"].ToString().ToString() == "0")
            {
                EAddressInfo addrmodel = new EAddressInfo();
                addrmodel.Receiver = infoaddress.OrderRcver;
                addrmodel.Address = infoaddress.AddressText;
                addrmodel.BuildingID = 0;
                addrmodel.Phone = infoaddress.OrderComm;
                addrmodel.Mobilephone = infoaddress.OrderComm;
                addrmodel.UserID = 0;
                addrmodel.AddTime = DateTime.Now;
                addrmodel.Pri = 0;
                addrmodel.Lat = ulat;
                addrmodel.Lng = ulng;

                int userid = new EAddress().SaveUserAndAddress(addrmodel);
            }

        }

        return JsonConvert.SerializeObject(rs);
    }

    /// <summary>
    /// 计算配送费
    /// </summary>
    public string getSendFee()
    {
        string shopid = WebUtility.InputText(base._httpReuqest["shopid"]);
        string lat = WebUtility.InputText(base._httpReuqest["lat"]);
        string lng = WebUtility.InputText(base._httpReuqest["lng"]);
        string price = WebUtility.InputText(base._httpReuqest["price"]);
        if (price.Length == 0)
        {
            price = "0";
        }

        SendfeeInfo info = new SendfeeInfo();
        info.ShopID = Convert.ToInt32(shopid);
        info.userpay = Convert.ToDecimal(price);
        info.latlng = new latlnginfo();
        info.latlng.ulat = lat;
        info.latlng.ulng = lng;

        SendFee fee = new SendFee(info);
        SendInfo model = fee.getSendFee();


        return JsonConvert.SerializeObject(model);
    }


    /// <summary>
    /// 根据电话获取地址信息
    /// </summary>
    /// <returns></returns>
    public string getaddressByTel()
    {
        string tel = WebUtility.InputText(base._httpReuqest["tel"]);
        string SqlWhere = "  EXISTS (SELECT DataID FROM dbo.ECustomer WHERE DataID = dbo.EAddress.UserID AND (Name = '" + tel + "' or Tell ='" + tel + "') ) ";

        IList<EAddressInfo> list = new EAddress().GetList(10, 1, SqlWhere, "AddTime", 1);

        return JsonConvert.SerializeObject(list);
    }

    /// <summary>
    /// 获取更多商家
    /// </summary>
    public string loadshop()
    {
        string res = "";


        return res;
    }
    public string changeadd()
    {
        EAddress dal = new EAddress();
        int aid = Convert.ToInt32(base._httpReuqest["aid"]);
        int uid = Convert.ToInt32(base._httpReuqest["uid"]);
        int rs = dal.UpdateDefaut(aid, uid);
        return rs.ToString();
    }

    public int addtogo()
    {
        ETogoCollect bll = new ETogoCollect();
        int togoid = Convert.ToInt32(base._httpReuqest["togoid"]);
        int userid = Convert.ToInt32(base._httpReuqest["userid"]);
        int bid = Convert.ToInt32(base._httpReuqest["bid"]);
        int msg = bll.TogoCollect(userid, togoid, bid);
        return msg;
    }

    public int delete()
    {
        EAddress dal = new EAddress();
        int aid = Convert.ToInt32(base._httpReuqest["aid"]);
        int msg = dal.DelEAdd(aid);
        return msg;
    }
}